<!-- 账号管理 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px;">
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
          <span style="color:#d2d7e3;font-size:25px;margin-top:10px;padding-left:10px;">
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i>
              <div style="width: 420px;" slot="content">通过拖动表格行来重新排列顺序, 系统按次序从上到下优先级执行。添加放到所有规则最后，插入表示在当前策略前插入一条规则</div>
            </el-tooltip>
          </span>
        </div>
      </div>
      <el-table stripe border :data="tableData" class="draggable-table" row-key="RuleName"
        style="width: 100%; margin-top: 15px" height="calc(100vh - 155px)">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="规则名称" prop="RuleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="规则状态" show-overflow-tooltip prop="IsValid" width="160px">
          <template slot-scope="{row}">
            <span style="color:#67C23A" v-if="row.IsValid === 1" type="success">正常</span>
            <span style="color:#F56C6C" v-else type="danger">失效</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象类型" show-overflow-tooltip prop="DeviceObjType" width="120px">
          <template slot-scope="{row}">
            <span>{{ DeviceObjTypeFormatter(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px">
          <template slot-scope="{row}">
            <span>{{ getDeviceObjDisplay(row, DepartmentList, AssetsList) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检测间隔" show-overflow-tooltip prop="Interval" width="160px"></el-table-column>
        <el-table-column label="备注信息" show-overflow-tooltip prop="Descp"></el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false
      :title="Action === 1 ? '添加规则' : '修改规则'" :visible.sync="dialogVisible" v-el-drag-dialog width="800px">
      <el-form label-width="130px" ref="accountForm" :model="accountForm" :rules="rules" class="ruleDialogForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">基本规则内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称：' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName" :disabled="Action !== 1" :maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则状态：' prop="IsVaclid" style="margin-top:-10px;">
              <el-radio v-model="accountForm.IsValid" :label="1">正常</el-radio>
              <el-radio v-model="accountForm.IsValid" :label="0">失效</el-radio>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <device-object-selector :form.sync="accountForm" />
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="备注信息：" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" maxlength="50" :rows="3"
                v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleOther">
          <el-divider content-position="left">节能规则内容</el-divider>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='检测间隔：' prop="Interval">
              <el-input v-model.trim="accountForm.Interval" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">秒钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='关闭显示器：' prop="AutoCloseMonitor">
              <el-input v-model.trim="accountForm.AutoCloseMonitor" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">分钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （0表示不限制）
            </span>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='指定亮度：' prop="Lighter">
              <el-input v-model.trim="accountForm.Lighter" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （0表示不限制）
            </span>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='停止硬盘：' prop="AutoCloseDisk">
              <el-input v-model.trim="accountForm.AutoCloseDisk" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">分钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （0表示不限制）
            </span>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='在此时间后睡眠：' prop="AutoStandby">
              <el-input v-model.trim="accountForm.AutoStandby" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">分钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （0表示不限制）
            </span>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='自动关机时间点：' prop="AutoPowerOff">
              <el-time-picker v-model="accountForm.AutoPowerOff" placeholder="请选择自动关机时间点" value-format="HH:mm"
                format="HH:mm" style="width:100%"></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （空表示不限制）
            </span>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='工作时间定义：' prop="WorkDay" :key="WorkStartTime">
              <el-select v-model="accountForm.WorkDay" multiple placeholder="请选择" style="width: 100%;margin-bottom: 10px;"> 
                <el-option label="周一" :value="1"></el-option>
                <el-option label="周二" :value="2"></el-option>
                <el-option label="周三" :value="3"></el-option>
                <el-option label="周四" :value="4"></el-option>
                <el-option label="周五" :value="5"></el-option>
                <el-option label="周六" :value="6"></el-option>
                <el-option label="周日" :value="0"></el-option>
              </el-select>
              <el-time-select placeholder="起始时间" v-model="WorkStartTime" value-format="HH:mm" format="HH:mm"  :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '23:30'
              }"  style="margin-right:10px;">
              </el-time-select>
              <el-time-select placeholder="结束时间" v-model="WorkEndTime" value-format="HH:mm" format="HH:mm" :picker-options="{
                start: '00:00',
                step: '00:30',
                end: '23:30',
                minTime: WorkStartTime
              }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='非工作时间：' prop="nonWorkingHours">
              开机，执行指定动作：
              <el-select v-model="accountForm.SpecifyAction" placeholder="请选择动作" style="width: 100%;">
                <el-option label="强制关机" :value="1"></el-option>
                <el-option label="形成一条高危事件" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Sortable from "sortablejs";
import { getDeviceObjDisplay, DeviceObjTypeFormatter } from '@/utils/index.js';
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
export default {
  directives: { elDragDialog },
  components: {
    DeviceObjectSelector
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      RoleList: [],
      Action: 1,
      dialogVisible: false,
      accountForm: {},
      WorkStartTime: '9:00',
      WorkEndTime: '18:00',
      DeviceObjList: [],
      AssetsList: [],
      DepartmentList: [],
      rules: {
        RuleName: [
          { required: true, message: "请输入规则名称" }
        ],
        // Interval: [
        //   {
        //     validator: (rule, value, callback) => {
        //       // 使用正则表达式检查是否包含非数字字符 
        //       if (/[^0-9]/.test(value)) {
        //         // 不调用 callback，不显示错误提示
        //       } else {
        //         callback();
        //       }
        //     },
        //     trigger: 'blur'
        //   }
        // ]
      },
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetDevice()
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initSort();
  },
  methods: {
    DeviceObjTypeFormatter,
    getDeviceObjDisplay,
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    // 获取所有资产
    async GetDevice() {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
      }
      const res = await connrequest('GetDevice', data)
      this.AssetsList = res.Data
    },
    initSort() {
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      // 根据具体需求配置options配置项
      const sortable = new Sortable(el, {
        animation: 500, // 拖拽时的动画时长
        onEnd: async (evt) => { // 监听拖动结束事件
          // 下面将拖拽后的顺序进行修改
          const currRow = this.tableData.splice(evt.oldIndex, 1)[0]
          this.tableData.splice(evt.newIndex, 0, currRow)
          const newData = []
          this.tableData.forEach((item, index) => {
            newData[index] = {
              id: item.id,
              rank: index + 1
            }
          })
          const data = {
            Data: {
              OpFile: 2,
              List: [...this.tableData]
            }
          }
          const res = await connrequest('ReorderList', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success('排序成功')
            this.getData()
          }
        }
      })
    },
    async getData() {
      const res = await connrequest('GetEnergySavingRule')
      this.tableData = res.Data
    },
    addClick() {
      this.Action = 1
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs['accountForm']) {
          this.accountForm = {
            IsValid: 1,
            DeviceObjType: 1,
            Interval: 30,
            AutoCloseMonitor: 0,
            Lighter: 60,
            AutoCloseDisk: 0,
            AutoPowerOff: 0,
            AutoStandby: 0,
            DeviceObj: [],
            WorkDay: [1,2,3,4,5],
            SpecifyAction: 2
          }
          this.$set(this, 'WorkStartTime', '09:00');
          this.$set(this, 'WorkEndTime', '18:00');
          this.$refs['accountForm'].clearValidate();
        }
      })
    },
    changeClick(row, index) {
      this.Action = 2
      this.$nextTick(() => {
        this.accountForm = { ...row, AutoPowerOff: row.AutoPowerOff === '24:00' ? '' : row.AutoPowerOff }
        this.$set(this, 'WorkStartTime', row?.WorkTime?.[0]);
        this.$set(this, 'WorkEndTime', row?.WorkTime?.[1]);
        this.$refs['accountForm'].clearValidate();
      })
      // this.WorkStartTime = row?.WorkTime?.[0]
      // this.WorkEndTime = row?.WorkTime?.[1]
      this.dialogVisible = true
    },
    deleteClick(row) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {
          Data: {
            Action: 3,
            Detail: { ...row }
          }
        }
        const res = await connrequest('EditEnergySavingRule', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit() {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if (this.accountForm.DeviceObjType === 2) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择部门')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 8) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择角色')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 6) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择资产')
              return false
            }
          }
          if (this.accountForm.Interval < 1) {
            this.$message.error('检测间隔最少为1秒')
            return
          }
          let data = {
            Data: {
              Action: this.Action,
              Detail: { 
                ...this.accountForm, 
                AutoPowerOff: this.accountForm.AutoPowerOff ? this.accountForm.AutoPowerOff : '24:00',
                WorkTime: [this.WorkStartTime, this.WorkEndTime]
              }
            }
          }
          const res = await connrequest('EditEnergySavingRule', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success(this.Action == 1 ? '添加成功' : '修改成功')
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    handleChange(row) { },
  }
}
</script>